<template>
	<ElRate
	  v-model="props.data[props.field.name]"
	  :texts="texts"
	  show-text
	  clearable
	/>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import type { PropType } from 'vue'
import { DictService } from '@/api/sys/dictApi'

const emit = defineEmits(['update:value'])

const props = defineProps({
  field: {
    type: Object as PropType<Record<string, any>>,
    required: true,
    default: () => ({}),
    validator: (field: any) => {
      if (field.mapping === 'dict' && !field.mappingKey) {
        console.warn('当使用字典映射时，必须提供 mappingKey')
        return false
      }
      return true
    }
  },
  data: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
})

// 计算属性
const placeholderText = computed(() => {
  return props.field.placeholder || `请选择${props.field.label || ''}`
})

const clearable = computed(() => {
  return props.field.clearable ?? true
})

const filterable = computed(() => {
  return props.field.filterable ?? true
})

// 选项数据
const fieldOptions = ref<any[]>([])

const texts = ref<string[]>([])
const loading = ref(false)
const dropdownVisible = ref(false)

// 获取选择项数据
const getSelectOptions = async () => {
  try {
    if (props.field.mapping === 'dict' && props.field.mappingKey) {
      loading.value = true
      const data = await DictService.getSelectOptions(props.field.mappingKey)
      fieldOptions.value = Array.isArray(data) ? data : []
	  
    } else {
      fieldOptions.value = Array.isArray(props.field.options) 
        ? props.field.options 
        : []
    }
	texts.value=[];
	for(var f of fieldOptions.value){
		texts.value.push(f.cnLabel)
	}
  } catch (error) {
    console.error('获取选项数据失败:', error)
    fieldOptions.value = []
	texts.value=[];
  } finally {
    loading.value = false
  }
}

// 监听下拉框可见状态变化
const handleDropdownVisible = (visible: boolean) => {
  dropdownVisible.value = visible
  // 如果下拉框打开且选项为空，重新获取数据
  if (visible && fieldOptions.value.length === 0) {
    getSelectOptions()
  }
}

// 双向绑定值
const fieldValue = computed({
  get: () => props.data[props.field.name],
  set: (value) => {
    emit('update:value', value)
  }
})

// 监听field.mappingKey变化重新获取数据
watch(
  () => props.field.mappingKey,
  (newKey, oldKey) => {
    if (newKey && newKey !== oldKey) {
      getSelectOptions()
    }
  }
)

// 初始化时获取数据
watch(
  () => props.field.mapping,
  getSelectOptions,
  { immediate: true }
)
</script>